﻿Imports System.ComponentModel.DataAnnotations
Imports System.ComponentModel.DataAnnotations.Schema
Imports PowerShellCron.Service.SecurityManager

Public Class SecurityUser
    Public Property SecurityUserId As Integer
    <Index("IX_Name", isunique:=True)> <Required> <MaxLength(150)>
    Public Property Name As String
    <EmailAddress> <MaxLength(150)>
    Public Property Email As String
    Public Property IsGroup As Boolean

    Public Overridable Property Roles As ICollection(Of SecurityRole)

    Public Sub New()
        Me.Roles = New HashSet(Of SecurityRole)()
    End Sub
End Class

Public Class SecurityRole
    Public Property SecurityRoleId As Integer
    <Index("IX_Name", isunique:=True)> <Required> <MaxLength(50)>
    Public Property Name As String
    Public Property Description As String

    Public Overridable Property Members As ICollection(Of SecurityUser)
    Public Overridable Property Access As ICollection(Of SecurityRoleAccess)

    Public Sub New()
        Me.Members = New HashSet(Of SecurityUser)()
        Me.Access = New HashSet(Of SecurityRoleAccess)()
    End Sub
End Class

<Table("SecurityRoleAccess")>
Public Class SecurityRoleAccess
    Public Property SecurityRoleAccessID As Integer
    Public Property ObjectType As String
    Public Property ObjectID As Integer?
    Public Property Permissions As Integer

    <NotMapped>
    Private WithEvents _permissionList As New List(Of Permission)

    Public Sub New()
        For Each p As Integer In [Enum].GetValues(GetType(Permission))
            If Me.Permissions And p Then Me._permissionList.Add(p)
        Next
    End Sub

    Public Function PermissionList() As Permission()
        Return Me._permissionList.ToArray
    End Function

    Public Sub AddPermission(permission As Permission)
        If Not Me._permissionList.Contains(permission) Then
            Me._permissionList.Add(permission)
            Me.Permissions = Me.Permissions Or permission
        End If
    End Sub

    Public Sub RemovePermission(permission As Permission)
        If Me._permissionList.Contains(permission) Then
            Me._permissionList.Remove(permission)
            Me.Permissions = Me.Permissions Xor permission
        End If
    End Sub

    Public Property SecurityRoleId As Integer
    Public Overridable Property Role As SecurityRole
End Class